import { getRepository } from 'typeorm';
import { NextFunction, Request, Response } from 'express';
import { User } from '../entity/User';
import { v1 as uuidv1 } from 'uuid';
import { successRes, failRes } from '../utils/response';
// const userService = require('../service/user');
const { goLogin } = require('../service/user');
export class UserController {
  private userRepository = getRepository(User);

  async all(request: Request, response: Response, next: NextFunction) {
    try {
      const { pageNo, pageSize, username, roleId } = request.query;
      var data = [];
      var total = 0;
      let queryBuilder = this.userRepository.createQueryBuilder('user');
      if (username) {
        queryBuilder = queryBuilder.andWhere('user.username like :username', { username: '%' + username + '%' });
      }
      if (roleId) {
        queryBuilder = queryBuilder.andWhere('user.roleId = :roleId', { roleId: roleId });
      }
      queryBuilder = queryBuilder.leftJoinAndSelect('user.role', 'role');
      queryBuilder = queryBuilder.skip((pageNo - 1) * pageSize).take(pageSize);
      queryBuilder = queryBuilder.orderBy('user.createdDate', 'DESC');
      data = await queryBuilder.getMany();
      total = await queryBuilder.getCount();
      let result = {
        current: pageNo,
        records: data,
        size: pageSize,
        total: total,
      };
      return successRes(result);
    } catch (error) {
      return failRes(error);
    }
  }

  async one(request: Request, response: Response, next: NextFunction) {
    return this.userRepository.findOne(request.params.id);
  }

  async register(request: Request, response: Response, next: NextFunction) {
    try {
      const toSave = request.body;
      toSave.token = uuidv1();
      let user = await this.userRepository.findOne({ username: toSave.username });

      if (user) {
        return {
          message: '添加失败,系统中已存在该用户',
          success: false,
        };
      }
      let obj = await this.userRepository.save(toSave);
      if (obj.id) {
        return {
          message: '注册成功',
          success: true,
        };
      } else {
        return {
          message: '添加失败',
          success: false,
        };
      }
    } catch (error) {
      return {
        err: error,
        message: '服务器报错了',
        success: false,
      };
    }
  }
  async add(request: Request, response: Response, next: NextFunction) {
    try {
      const toSave = request.body;
      let user = await this.userRepository.findOne({ username: toSave.username });
      if (user) {
        return {
          message: '添加失败,系统中已存在该用户',
          success: false,
        };
      }
      toSave.password = '123456';
      toSave.token = uuidv1();
      let obj = await this.userRepository.save(toSave);
      if (obj.id) {
        return successRes('添加成功');
      } else {
        return failRes('添加失败');
      }
    } catch (error) {
      return failRes(error);
    }
  }

  async remove(request: Request, response: Response, next: NextFunction) {
    try {
      let userToRemove = await this.userRepository.findOne(request.query.id);
      if (userToRemove) {
        if (userToRemove.type == 'system') {
          return failRes({}, 500, '管理员账号不能删除');
        }
        await this.userRepository.remove(userToRemove);
        return successRes({}, '删除成功');
      } else {
        return failRes({}, 500, '未找到该用户');
      }
    } catch (error) {
      return failRes(error);
    }
  }
  async login(request: Request, response: Response, next: NextFunction) {
    const { username, password } = request.body;
    let result = await goLogin(username, password);
    console.log(`result`, result)
    if (result.success) {
      return {
        code: 200,
        ...result,
      };
    } else {
      return {
        code: 400,
        ...result,
      };
    }

    // return this.userRepository.findOne(request.params.id);
  }
  async bindRole(request: Request, response: Response, next: NextFunction) {
    const { roleId, userIdList } = request.body;

    let result = await this.userRepository.update(userIdList, { roleId: roleId });
    console.log(`result`, result);
    return successRes('绑定成功');
  }
}
